<template>
  <div class="jaguar-view">
    <div class="jaguar-search" />
    <div class="jaguar-control">
      <add-button @click="handleCreate" />
    </div>

    <Card>
      <template #content>
        <TreeTable :value="tableData" :loading="loading">
          <Column field="deptName" header="部门名称" expander />
          <Column header="操作">
            <template #body="scope">
              <view-button @click="handleView(scope.node.data)" />
              <edit-button @click="handleEdit(scope.node.data)" />
              <delete-button @confirm="handleDelete(scope.data)" />
            </template>
          </Column>
        </TreeTable>
      </template>
    </Card>

    <Edit :dialog="dialog" @success="getData()" />
  </div>
</template>
<script>
import { tree2TableData } from '@/utils'
import { fetchList, del } from '@/api/upms/dept'
import Edit from './Edit'

export default {
  name: 'Dept',
  data() {
    return {
      loading: false,
      tableData: [],
      dialog: {
        entity: null,
        operation: null,
        visible: false,
      },
    }
  },
  components: {
    Edit,
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData() {
      this.loading = true

      fetchList()
        .then((res) => {
          this.tableData = tree2TableData(res.data.data, 'id', 'deptName')
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleCreate() {
      this.dialog.entity = null
      this.dialog.operation = 1
      this.dialog.visible = true
    },
    handleEdit(row) {
      this.dialog.entity = row
      this.dialog.operation = 2
      this.dialog.visible = true
    },
    handleView(row) {
      this.dialog.entity = row
      this.dialog.operation = 3
      this.dialog.visible = true
    },
    handleDelete(row) {
      del(row.id).then(() => {
        this.$message.success('删除成功')
        this.getData()
      })
    },
  },
}
</script>
